import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance 接口前缀
const service = axios.create({
  baseURL: `${process.env.VUE_APP_BASE_API}`
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
      config.headers['companyId'] = 78
    }

    config.headers['isNotEncrypt'] = 1

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
    }

    // if the custom code is not 20000, it is judged as an error.
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

const get = (url, params = {}) => {
  return service({
    url,
    method: 'get',
    params: {
      timestamp: new Date().getTime(),
      ...params
    }
  })
}

const post = (url, data, config = {}) => {
  return service({
    url,
    method: 'post',
    data,
    ...config
  })
}

/**
 * 附件下载
 * @param {string} fileName 文件名
 */
const downFile = (fileName) => {
  const downTag = document.createElement('a')
  downTag.setAttribute('download', fileName.lastIndexOf('_') !== -1 ? fileName.slice(fileName.lastIndexOf('_') + 1) : fileName)
  // 都使用8080 后期可能会改
  const isRelease = (process.env.VUE_APP_ENV || '').startsWith('release')
    ? (process.env.VUE_APP_ENV === 'release1' ? 'http://172.28.1.232:8080' : 'http://172.28.1.232:8080') : process.env.VUE_APP_BASE_API
  downTag.setAttribute('href', `${isRelease}/storage/${fileName}`)
  downTag.style.display = 'none'
  document.body.appendChild(downTag)
  downTag.click()
  document.body.removeChild(downTag)
}

export {
  get,
  post,
  downFile
}

export default service
